package cn.edu.whu.forecast.util;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class test {
    public static void main(String[] args) {
        String fileName = "test.xlsx";
        createExcel(fileName);
        appendToExcel(fileName);
    }

    private static void createExcel(String fileName) {
        try (FileOutputStream fos = new FileOutputStream(fileName)) {
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet("测试");
            HSSFRow row0 = sheet.createRow(0);
            row0.createCell(0).setCellValue("第一列");
            row0.createCell(1).setCellValue("第二列");
            workbook.write(fos);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void appendToExcel(String fileName) {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(fileName);
            HSSFWorkbook workbook = new HSSFWorkbook(fis);
            HSSFSheet sheet = workbook.getSheet("测试");
            if (sheet != null) {
                sheet.getRow(0).createCell(2).setCellValue("第三列");
            }
            fos = new FileOutputStream(fileName);
            workbook.write(fos);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                //ignore
            }

        }

    }
}
